package com.huike.web.controller.common;

import com.huike.common.config.HuiKeConfig;
import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.UploadFileAjaxResult;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.file.AliOssUtil;
import com.huike.common.utils.file.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description 通用请求处理
 * @Date 2023-10-10
 */
@Api(tags = "通用请求相关接口")
@RestController
public class CommonController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private AliOssUtil aliOssUtil;

    @ApiOperation("通用下载请求")
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = HuiKeConfig.getDownloadPath() + fileName;
            log.info("下载路径 {}", filePath);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @ApiOperation("通用上传请求")
    @PostMapping("/common/upload")
    public UploadFileAjaxResult uploadFile(MultipartFile file) throws Exception{
        try{
            log.info("文件上传接口:{}",file);

            //获取原始文件名
            String originalFilename = file.getOriginalFilename(); //xxxxxx.jpg

            //获取后缀
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));//.jpg

            //设置上传文件名=UUID+原始文件名后缀
            String fileName = UUID.randomUUID().toString().replace("-","") + extName;

            //调用工具类实现文件上传
            String path = aliOssUtil.upload(file.getBytes(), fileName);
            UploadFileAjaxResult ajax = UploadFileAjaxResult.success();
            ajax.setFileName(fileName);
            ajax.setUrl(path);
            return ajax;
        }catch (Exception e){
            return UploadFileAjaxResult.error(e.getMessage());
        }
    }

}
